﻿package vklib 
{
	import flash.net.*;
	/**
	 * ...
	 * @author apisoc@gmail.com
	 */
	internal class VkRequest implements IVkRequest
	{
		private var _args:Object;
		private var _result:VkRequestResult = new VkRequestResult();
		private var _viewer:String;
		
		public function VkRequest(params:Object) 
		{
			_viewer = params.viewer_id;
			_result.request.url = params.api_url;
			_args = { v: '2.0', api_id: params.api_id, test_mode: params.test_mode };
		}
		
		private function makeSig(vars:Object):String
		{
			var pairs:Array = [];
			for (var i:String in vars) {
				var p:* = { name: i, value: vars[i] };
				p.toString = function():String { return this.name + '=' + this.value; }
				pairs.push(p);
			}
			pairs.sortOn('name');
			return MD5.encrypt(_viewer + pairs.join('') + VkApi.settings.secret);
		}
		
		private function send(method:String, params:Object, isPost:Boolean = true):IResult
		{
			var vars:URLVariables = new URLVariables();
			vars.method = method;
			for (var i:String in _args)
				vars[i] = _args[i];
			for (i in params)
				vars[i] = params[i];
			vars.sig = makeSig(vars);
			
			with (_result.request) {
				data = vars;
				method = isPost ? URLRequestMethod.POST : URLRequestMethod.GET;
			}
			return _result;
		}
		
		public function getFriends():IResult
		{
			return send('getFriends', null, false);
		}
				
		public function getProfiles(uids:Array, fields:Array = null):IResult
		{
			var params:Object = { uids: uids.toString() };
			if (fields) params.fields = fields.toString();
			return send('getProfiles', params);
		}
		
		public function getFriendProfiles(fields:Array = null):IResult
		{
			var code:String = 'return API.getProfiles({"uids": API.getFriends()';
			if (fields.length)
				code += ', "fields": "' + fields.toString() + '"';
			code += '});';
			return executeScript(code);
		}

		public function sendMessage(text:String):IResult
		{
			return send('sendMessage', { message: text });
		}

		public function executeScript(code:String):IResult
		{
			return send('execute', { code: code });
		}
	}

}